package com.meizu.asum.richtextsdk.tools.selectpictools.tools;

import android.app.Activity;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;

/**
 * 权限工具类
 *
 * @Author XJW
 * @CreateTime 2016/11/2
 */
public class PermissionTools {
    private static final int CODE = 2016;
    private PermissionToolsCallBack callBack;

    public void check(Activity activity, PermissionToolsCallBack callBack, String... permission) {
        this.callBack = callBack;

        String[] needApply = new String[permission.length];
        int count = 0;

        for (int i = 0; i < permission.length; i++) {
            if (ContextCompat.checkSelfPermission(activity, permission[i]) != PackageManager.PERMISSION_GRANTED) {
                needApply[count] = permission[i];
                count++;
            }
        }

        if (count == 0) {
            if (callBack != null) {
                int[] grantResults = new int[permission.length];
                for (int i = 0; i < permission.length; i++) {
                    grantResults[i] = PackageManager.PERMISSION_GRANTED;
                }
                callBack.requestResult(permission, grantResults);
            }
        } else {
            ActivityCompat.requestPermissions(activity, permission, CODE);
        }
    }

    public boolean haveThisPermissions(Activity activity, String... permission) {
        for (int i = 0; i < permission.length; i++) {
            if (ContextCompat.checkSelfPermission(activity, permission[i]) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == CODE) {
            if (callBack != null) {
                callBack.requestResult(permissions, grantResults);
            }
        }
    }

    public interface PermissionToolsCallBack {
        /**
         * @param permissions
         * @param grantResults 值为PackageManager.PERMISSION_DENIED代表申请失败，值为PackageManager.PERMISSION_GRANTED代表申请成功
         */
        void requestResult(String[] permissions, int[] grantResults);
    }
}
